package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车管理
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R addShoppingCart(@RequestBody ShoppingCart shoppingCart) {
        log.info("购物车：{}", shoppingCart);

        // 获取session中用户id， 设置用户id
        //Long userId = (Long) httpSession.getAttribute("user");
        //通过threadlocal获取session中用户id， 设置用户id
        Long currentId = BaseContext.getCurrentId();

        //设置用户id，指定当前是哪个用户的购物车数据
        shoppingCart.setUserId(currentId);

        //1.判断当前点的菜品/套餐 购物车是否已存在
        // select * from shopping_cart
        // where (dish_id = ? 或 setmeal_id = ? ) and user_id = ？

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(ShoppingCart::getUserId, currentId);
        //判断当前用户点的是菜品还是套餐
        //如果是菜品：select * from shopping_cart where dish_id = ? and user_id = ?
        //如果是套餐：select * from shopping_cart where setmeal_id = ? and user_id = ?
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        if (dishId != null) {
            //添加到购物车的是菜品
            queryWrapper.eq(shoppingCart.getDishId()!=null,ShoppingCart::getDishId, dishId);
        } else {
            //添加到购物车的是套餐
            queryWrapper.eq(shoppingCart.getSetmealId()!=null,ShoppingCart::getSetmealId, setmealId);
        }

        ShoppingCart oneFromSql = shoppingCartService.getOne(queryWrapper);
        // 第一次点的时候是新增 ，后面再点击的时候是修改
        if (oneFromSql == null) {
            //如果不存在，则是新增
            // 设置 number=1
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(currentId);
            shoppingCartService.save(shoppingCart);
            oneFromSql = shoppingCart;
        } else {
            //如果存在，则是更新
            oneFromSql.setNumber(oneFromSql.getNumber() + 1);
            shoppingCartService.updateById(oneFromSql);
        }
        return R.success(oneFromSql);
    }

    /**
     * 查询购物车列表
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        log.info("查看购物车：");
        // select * from shopping_cart where user_id =?
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();

        //通过threadlocal获取session中用户id
        Long userId = BaseContext.getCurrentId();
        //Long userId = (Long) httpSession.getAttribute("user");
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        queryWrapper.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 取消购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R<ShoppingCart> subShoppingCart(@RequestBody ShoppingCart shoppingCart) {
        //菜品或者套餐id 查询出当前ShoppingCart数据
        // 如果是菜品：select * from shopping_cart where dish_id = ? and user_id = ?
        // 如果是套餐：select * from shopping_cart where setmeal_id = ? and user_id = ?

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();

        // where user_id = ?
        Long userId = BaseContext.getCurrentId();
        queryWrapper.eq(ShoppingCart::getUserId, userId);

        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        if (dishId != null) {
            //为菜品   dish_id = ?
            queryWrapper.eq(ShoppingCart::getDishId, dishId);
        } else {
            //为套餐   // setmeal_id = ?
            queryWrapper.eq(ShoppingCart::getSetmealId, setmealId);
        }
        ShoppingCart one = shoppingCartService.getOne(queryWrapper);

        Integer number = one.getNumber();
        // number - 1 后操作
        number--;
        one.setNumber(number);
        if (number > 0) {
            // number > 0 更新 update set number = ? where id = ?
            shoppingCartService.updateById(one);
        } else {
            // <= 0  如何操作？ delete from shopping_cart where dish_id=? and user_id = ?
            shoppingCartService.remove(queryWrapper);
        }
        return R.success(one);
    }

    /**
     * 清空购物车
     *
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> cleanShoppingCart() {
        // 根据当前用户id进行删除：
        // delete from shoping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        shoppingCartService.remove(queryWrapper);
        return R.success("清空购物车成功！");
    }
}
